package com.atguigu.controller;

import com.atguigu.entity.House;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.service.HouseService;
import com.atguigu.util.FileUtil;
import com.atguigu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController {

    @DubboReference
    private HouseImageService houseImageService;

    @DubboReference
    private HouseService houseService;

    //进入上传房源/房产页面
    @GetMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable("houseId") Long houseId,
                             @PathVariable("type") Integer type,
                             Model model
                             ) {
        //将houseId和type存储到请求域
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);
        //显示图片上传页面
        return "house/upload";
    }

    /**
     * 图片上传
     * 异步请求，路径：/houseImage/upload/{houseId}/{type}
     * 请求参数：file
     * 响应数据：Result.ok
     */
    @ResponseBody
    @PostMapping("/upload/{houseId}/{type}")
    public Result upload(@PathVariable("houseId") Long houseId,
                         @PathVariable("type") Integer type,
                         @RequestParam("file") List<MultipartFile> fileList) throws IOException {
        //1.先要遍历处上传的每一个文件
        if(!CollectionUtils.isEmpty(fileList)) {
            for (int i = 0; i < fileList.size(); i++) {
                MultipartFile multipartFile = fileList.get(i);
                System.out.println("888888888888");
                //2.将每个文件上传到七牛云
                //2.1上传的每一张图片要有唯一文件名
                String uuidName = FileUtil.getUUIDName(multipartFile.getOriginalFilename());
                //2.2创建3级目录结构
                String dateDirPath = FileUtil.getDateDirPath();
                String fileName = dateDirPath + uuidName;
                System.out.println("dateDirPath = " + dateDirPath);
                System.out.println("fileName = " + fileName);
                QiniuUtil.upload2Qiniu(multipartFile.getBytes(), fileName);
                //3.将上传的图片大访问路径、在七牛云中的路径、上传的图片对应的房源id保存到hse_house_image
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setImageName(fileName);
                String url = QiniuUtil.getUrl(fileName);
                houseImage.setImageUrl(url);
                houseImage.setType(type);
                houseImageService.insert(houseImage);
                //4.判断房源是否有默认图片，如果没有可以将这次上传的第一张图片设置为当前房源的第一张照片
                if (i == 0) {
                    //根据id获取房源信息
                    House house = houseService.getById(houseId);
                    //获取房源默认图片路径
                    String defaultImageUrl = house.getDefaultImageUrl();
                    if (StringUtils.isEmpty(defaultImageUrl) || "null".equalsIgnoreCase(defaultImageUrl)) {
                        //当前房源没有默认图片,进行设置
                        house.setDefaultImageUrl(url);
                        //更新发房源信息
                        houseService.update(house);
                    }
                }
            }
        }
        return Result.ok();
    }

    @GetMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable("houseId") Long houseId,
                         @PathVariable("id") Long id) {
        //1.从七牛云中删除这张图片
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        //2.从数据库表中删除图片
        houseImageService.delete(id);
        //3.若这张图片为房源默认图片，则修改房源默认图片为空
        //(1)查房源信息
        House house = houseService.getById(houseId);
        if (houseImage.getImageUrl().equals(house.getDefaultImageUrl())) {
            //当前删除的图片为房源默认图片
            house.setDefaultImageUrl("null");
            houseService.update(house);
        }
        return "redirect:/house/" + houseId;
    }
}
